package com.example.forumbackend.com.expection;

import com.example.forumbackend.com.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.LockedAccountException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @author chenguo
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * handle shiro exception and throw to frontend
     * @param e shiro exception
     * @return failed result
     * */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public Result handle401(ShiroException e){
        return Result.failed(401, e.getMessage(), null);
    }

    /**
     * handle Assert exception and throw to frontend
     * @param e Assert exception
     * @return failed result
     * */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e){
        log.error("Assert Error:----------->{}", e.getMessage());
        return Result.failed(e.getMessage());
    }

    /**
     * handle valid exception and throw to frontend
     * @param e valid exception
     * @return failed result
     * */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e){
        log.error("Validation Error:----------->{}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().orElse(null);
        assert objectError != null;
        return Result.failed(objectError.getDefaultMessage());
    }

    /**
     * handle runtime exception and throw to frontend
     * @param e runtime exception
     * @return failed result
     * */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e){
        log.error("Runtime Error:----------->{}", e.getMessage());
        return Result.failed(e.getMessage());
    }

    /**
     * handle locked exception and throw to frontend
     * @param e locked exception
     * @return failed result
     * */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(LockedAccountException.class)
    public Result handler(LockedAccountException e){
        log.error("Account is locked-------------{}", e.getMessage());
        return Result.failed(401, e.getMessage(), null);
    }

}
